package io.gitee.xjt2016.modules.controller;

import cn.hutool.http.HttpUtil;
import io.gitee.xjt2016.modules.common.BaseController;
import io.gitee.xjt2016.modules.common.utils.http.RestTemplateUtil;
import io.gitee.xjt2016.modules.domain.ApiSendRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Controller
@RequestMapping(value = "/demo")
public class DemoController extends BaseController {

    @GetMapping(value = {"tree"})
    public String treeIndex(ApiSendRequest request) throws Exception {
        return "/demo/tree";
    }

    @ResponseBody
    @GetMapping(value = "/treeData")
    public Object treeData(String keyword) {
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", i);
            String name = "name" + i;
            if (!StringUtils.containsIgnoreCase(name, keyword)) {
                continue;
            }
            map.put("name", name);
            list.add(map);
        }
        return buildSuccessResponse(list);
    }

    @ResponseBody
    @RequestMapping(value = {"/send"})
    public Object send(ApiSendRequest request) throws Exception {
        return "";
    }

    String url = "http://openapi-fxg.jinritemai.com/shop/currentShop?param_json={}&method=shop.currentShop&app_key=3385443310708636675&timestamp=2018-06-19 16:06:59&v=1&sign=905fb632c4c4f9f079ba2c8f2f617de9";

    @ResponseBody
    @RequestMapping(value = {"/test"})
    public Object test(ApiSendRequest request) throws Exception {
        CompletableFuture.runAsync(() -> {
            while (true) {
                CompletableFuture.runAsync(() -> {
                    try {
                        String str = RestTemplateUtil.getInstance().getForObject(url, String.class);
                        System.out.println(str);
                    } catch (Exception e) {

                    }
                });
            }
        });
        return "test";
    }


    @ResponseBody
    @RequestMapping(value = {"/test2"})
    public Object test2(ApiSendRequest request) throws Exception {
        CompletableFuture.runAsync(() -> {
            while (true) {
                CompletableFuture.runAsync(() -> {
                    try {
                        String str = HttpUtil.get(url);
                        System.out.println(str);
                    } catch (Exception e) {
                    }
                });
            }
        });
        return "test2";
    }
}
